package com.passcheck.anno;

import cn.hutool.json.JSONUtil;
import com.common.response.Result;
import com.common.response.ResultUtil;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author ZhangHaiWen
 * @title: ResponseResultBodyAdvice
 * @projectName park
 * @description: 全局数据统一返回格式配置 注解配置
 * @date 2020/11/2710:25
 */
// @Order(Ordered.HIGHEST_PRECEDENCE) 提升拦截的级别
@RestControllerAdvice
public class ResponseResultBodyAdvice implements ResponseBodyAdvice<Object> {

    /**
 　　* @description:
 　　* @param [returnType, converterType]
 　　* @return {@link boolean}
 　　* @throws
 　　* @author ZhangHaiWen
 　　* @version 2.0
 　　* @date 2020/11/27 10:27
 　　*/
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), ResponseResultBody.class) || returnType.hasMethodAnnotation(ResponseResultBody.class);
    }

    /**
 　　* @description:
 　　* @param [body, returnType, selectedContentType, selectedConverterType, request, response]
 　　* @return {@link Object}
 　　* @throws
 　　* @author ZhangHaiWen
 　　* @version 2.0
 　　* @date 2020/11/27 10:29
 　　*/
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 防止重复包裹的问题出现
        if (body instanceof Result) {
            return body;
        }
        return ResultUtil.SUCCESS(body);
    }
}
